import { Component, OnInit, ViewChild, TemplateRef } from '@angular/core';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { _HttpClient } from '@delon/theme';
import { tap, map } from 'rxjs/operators';
import { STComponent, STColumn, STData } from '@delon/abc';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import { AppInfoService } from '../../../../service/app-info.service'
import {
  FormBuilder,
  FormControl,
  FormGroup,
  Validators
} from '@angular/forms';

@Component({
  selector: 'app-info-list',
  templateUrl: './app-info-list.component.html',
})
export class AppInfoListComponent implements OnInit {
  validateForm: FormGroup;

  isVisible = false;
  isOkLoading = false;
  appId: String = undefined;
  isDetailVisible = false;
  q: any = {
    pi: 1,
    ps: 10,
    sorter: '',
    status: null,
    statusList: [],
  };
  data: any[] = [];
  loading = false;
  status = [
    { index: 0, text: '关闭', value: false, type: 'default', checked: false },
    {
      index: 1,
      text: '运行中',
      value: false,
      type: 'processing',
      checked: false,
    },
    { index: 2, text: '已上线', value: false, type: 'success', checked: false },
    { index: 3, text: '异常', value: false, type: 'error', checked: false },
  ];
  @ViewChild('st')
  st: STComponent;
  columns: STColumn[] = [
    { title: '', index: 'id', type: 'checkbox' },
    { title: '应用名称', index: 'appName' },
    { title: '应用类型', index: 'appType' },
    { title: '描述', index: 'remark' },
    {
      title: '更新时间',
      index: 'gmtCreate',
      type: 'date',
      sort: {
        compare: (a: any, b: any) => a.gmtCreate - b.gmtCreate,
      },
    },
    {
      title: '操作',
      buttons: [
        // {
        //   text: '详情',
        //   click: (item: any,modalContent: any) => this.detail(item,modalContent),
        // },
        {
          text: '修改',
          click: (item: any) => this.update(item),
        },
        {
          text: '删除',
          click: (item: any) => this.delete(item),
        },
      ],
    },
  ];
  selectedRows: STData[] = [];
  description = '';
  totalCallNo = 0;
  expandForm = false;

  constructor(
    private http: _HttpClient,
    public msg: NzMessageService,
    private modalSrv: NzModalService,
    private router: Router,
    private fb: FormBuilder,
    private appInfoService: AppInfoService
  ) {}

  ngOnInit() {
    // this.getData();
    this.getNewData();
    this.validateForm = this.fb.group({
      appName            : [ null, [  Validators.required ] ],
      description        : [ null, [ Validators.required ] ],
    });
  }

  getData() {
    this.loading = true;
    this.q.statusList = this.status
      .filter(w => w.checked)
      .map(item => item.index);
    if (this.q.status !== null && this.q.status > -1){
      this.q.statusList.push(this.q.status);
    }
    const params = {
      'body': {
          'pageInfo': {
              'page': this.q.pi,
              'pageSize': this.q.ps
          },
          'ruleDTO': {

          }
      }
    };
    this.http
      // .post<any>('http://127.0.0.1:9080/api/angular/angular/getTestTablePageList', params)
      .post<any>('/api/angular/angular/getTestTablePageList', params)
      .pipe(
        // map((response: any) =>
        //   response.body.ruleDTOList.map(i => {
        //     const statusItem = this.status[i.status];
        //     i.statusText = statusItem.text;
        //     i.statusType = statusItem.type;
        //     return i;
        //   }),
        // ),
        tap(() => (this.loading = false)),
      )
      .subscribe(response => (this.data = response.body.ruleDTOList,console.log(response.body.ruleDTOList)));
  }

  getNewData() {
    const heroesUrl: string = '/api/angular/angular/getAngularList';
    // const heroesUrl: string = 'http://127.0.0.1:9080/api/angular/angular/getAngularList';
    this.http
      .get(heroesUrl)
      .pipe(
        tap(() => (this.loading = false)),
      )
      .subscribe(res => (console.log(res)));

    this.appInfoService.queryAppInfoList(this.q.pi , this.q.ps , null)
      .pipe(
        tap(() => (this.loading = false)),
      )
      .subscribe(response => {this.data = response.body.appInfoDTOList; });
  }

  checkboxChange(list: STData[]) {
    this.selectedRows = list;
    this.totalCallNo = this.selectedRows.reduce(
      (total, cv) => total + cv.callNo,
      0,
    );
  }

  remove(item) {

  }

  approval() {
    this.msg.success(`审批了 ${this.selectedRows.length} 笔`);
  }

  resetForm(){
    this.validateForm = this.fb.group({
      appName            : [ null, [  Validators.required ] ],
      description        : [ null, [ Validators.required ] ],
    });
  }

  add(tpl: TemplateRef<{}>) {
    this.resetForm();
    // this.router.navigate(['/pro/list/test-rule-add']);
    this.modalSrv.create({
      nzTitle: '新建应用',
      nzContent: tpl,
      nzOnOk: () => {
        this.loading = true;

        for (const i in this.validateForm.controls) {
          this.validateForm.controls[ i ].markAsDirty();
          this.validateForm.controls[ i ].updateValueAndValidity();
        }
        // form表单校验无效(未通过)
        if (this.validateForm.invalid) {
          this.msg.error(`表单校验不通过！！!`);
          this.loading = false;
          return false;
        }

        const data = {
            'body': {
                'appInfoDTO': {
                    'appName': this.validateForm.controls['appName'].value,
                    'appType': 'APK',
                    'remark': this.validateForm.controls['description'].value
                }
            }
        };

        this.appInfoService.saveAppInfo(data)
          .subscribe(() => {
            this.loading = false;
            this.getNewData();
            this.msg.success(`保存成功!`);
        });
      },
    });
  }

  detail(item: any, modalContent: TemplateRef<{}>){
    console.log(modalContent);
    // console.log("detail"+item.key);
    // this.router.navigate(['/pro/list/test-rule-detail',{id: item.key, type: false}]);
    this.modalSrv.create({
      nzTitle: '应用详情',
      nzContent: modalContent,
      nzFooter: null,
      nzOnOk: () => {

      },
    });
    this.validateForm.patchValue({appName: item.appName});
    this.validateForm.patchValue({description: item.remark});
  }

  update(item: any){
    this.isVisible = true;
    this.appId = item.id;
    this.validateForm.patchValue({appName: item.appName});
    this.validateForm.patchValue({description: item.remark});
    // console.log("update"+item.key);
    // this.router.navigate(['/pro/list/test-rule-detail',{id: item.key, type: true}]);
  }

  delete(item: any){
    const data = {
        'body': {
            'appInfoDTO': {
                'id': item.id
            }
        }
    };

    this.appInfoService.deleteAppInfo(data)
      .subscribe(() => {
        this.getNewData();
        this.st.clearCheck();
      });
  }

  reset(ls: any[]) {
    for (const item of ls) item.value = false;
    this.getData();
  }

  handleOk(): void {
    this.isOkLoading = true;

    this.loading = true;

    for (const i in this.validateForm.controls) {
      this.validateForm.controls[ i ].markAsDirty();
      this.validateForm.controls[ i ].updateValueAndValidity();
    }
    // form表单校验无效(未通过)
    if (this.validateForm.invalid) {
      this.msg.error(`表单校验不通过！！!`);
      this.loading = false;
      return ;
    }

    const data = {
        'body': {
            'appInfoDTO': {
                'id': this.appId,
                'appName': this.validateForm.controls['appName'].value,
                'appType': 'APK',
                'remark': this.validateForm.controls['description'].value
            }
        }
    };

    this.appInfoService.updateAppInfo(data)
      .subscribe(() => {
        this.isVisible = false;
        this.isOkLoading = false;
        this.loading = false;
        this.getNewData();
        this.msg.success(`保存成功!`);
    });

  }

  handleCancel(): void {
    this.isVisible = false;
  }
}
